package com.dayu.finecomm.dsc.handler;

import com.dayu.finecomm.dsc.DSCInterface;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;


/**
 * 收到消息处理
 * @author hddz
 * @since 2017-07-27 15:48:20
 * @param <T>
 * @version V1.0
 */
public abstract class DSCHandler<T> extends SimpleChannelInboundHandler<T> {
	/**
	 * 回调接口
	 */
	protected DSCInterface mCallback = null;
	
	/**
	 * 处理从通道读取的数据
	 * @param ctx
	 * @param msg
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if (acceptInboundMessage(msg)) {
			channelRead0(ctx, (T) msg);
		} else {
			ctx.fireChannelRead(msg);
		}
	}
	
	/**
	 * 获取远端IP地址
	 * @param ctx
	 * @return
	 */
	protected String getIPString(ChannelHandlerContext ctx) {
		String ipString = "";
		String socketString = ctx.channel().remoteAddress().toString();
		int colonAt = socketString.indexOf(":");
		ipString = socketString.substring(1, colonAt);
		
		return ipString;
	}
	
	/**
	 * 获取远端IP地址
	 * @param msg DatagramPacket
	 * @return
	 */
	protected String getIPString(DatagramPacket msg) {
		String ipString = "";
		String socketString = msg.sender().toString();
		int colonAt = socketString.indexOf(":");
		ipString = socketString.substring(1, colonAt);
		
		return ipString;
	}
	
	/**
	 * 获取远端网络地址
	 * @param ctx
	 * @return
	 */
	protected String getRemoteAddress(ChannelHandlerContext ctx) {
		String socketString = "";
		socketString = ctx.channel().remoteAddress().toString();
		
		return socketString;
	}
	
	/**
	 * 获取远端网络地址
	 * @param msg DatagramPacket
	 * @return
	 */
	protected String getRemoteAddress(DatagramPacket msg) {
		String socketString = "";
		socketString = msg.sender().toString();
		
		return socketString;
	}
}
